"""
Case Type   : 资源池化集群DMS reform优化
Case Name   : kill主机进程->查看日志在recovery阶段允许出现flush动作
Create At   : 2024/05/13
Owner       : @kyleze
Description :
    1.设置参数log_min_message=log, logging_module='on(ALL)'
    2.执行tpcc
    3.kill主机进程
    4.查询集群状态
    5.查看日志中的刷盘动作
Expect      :
    1.成功
    2.成功
    3.成功
    4.集群恢复正常
    5.出现finish flush buffer
History     :
"""

import os
import unittest
import time

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.ComThread import ComThread

from yat.test import Node
from yat.test import macro


class DmsRform(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.dirname(__file__)} start----')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH("PrimaryDbUser")
        self.pri_user_node = Node(node="PrimaryDbUser")
        self.st1_user_node = Node(node="Standby1DbUser")
        self.st2_user_node = Node(node="Standby2DbUser")
        self.flush_num = int(self.pri_user_node.sh(
            f'source {macro.DB_ENV_PATH};grep "finish flush buffer" '
            f'{macro.PG_LOG}/dn_6001/*.log|wc -l').result())
        self.log.info('备份postgresql.conf文件')
        self.conf_file = os.path.join(
            macro.DB_INSTANCE_PATH, macro.DB_PG_CONFIG_NAME)
        pri_result = self.com.get_sh_result(
            self.pri_user_node, f"cp {self.conf_file} {self.conf_file}_bak")
        self.log.info(pri_result)
        st1_result = self.com.get_sh_result(
            self.st1_user_node, f"cp {self.conf_file} {self.conf_file}_bak")
        self.log.info(st1_result)
        st2_result = self.com.get_sh_result(
            self.st2_user_node, f"cp {self.conf_file} {self.conf_file}_bak")
        self.log.info(st2_result)

    def test_dms(self):
        step = "--step1:设置参数log_min_message=log, logging_module='on(ALL)' " \
               "expect:成功--'"
        self.log.info(step)
        setguc_res = self.primary_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            "log_min_message=log, logging_module='on(ALL)'")
        self.log.info(setguc_res)
        self.assertTrue(setguc_res, "执行失败" + step)
        stop_res = self.primary_sh.exec_cm_ctl("stop")
        self.log.info(stop_res)
        self.assertIn(
            self.constant.cm_stop_success_msg, stop_res, "执行失败" + step)
        start_res = self.primary_sh.exec_cm_ctl("start")
        self.log.info(start_res)
        self.assertIn(
            self.constant.cm_start_success_msg, start_res, "执行失败" + step)

        step = '--step2:执行tpcc expect:成功--'
        self.log.info(step)
        tpcc_cmd = f'. runBenchmark.sh {macro.TPCC_PROPS_FILENAME}'
        tpcc_thread = ComThread(
            self.com.start_tpcc,
            args=(Node(node='PrimaryRoot'), macro.TPCC_PATH, tpcc_cmd,))
        tpcc_thread.setDaemon(True)
        tpcc_thread.start()

        step = '--step3:kill主机进程 expect:成功--'
        self.log.info(step)
        time.sleep(300)
        kill_cmd = "ps ux | grep '\-D' | grep gaussdb | grep -v grep | " \
                   "awk '{print $2}' | xargs kill -9"
        kill_res = self.pri_user_node.sh(kill_cmd).result()
        self.log.info(kill_res)
        self.assertIn('', kill_res, "执行失败" + step)

        step = '--step4:查看集群状态 expect:集群状态正常--'
        self.log.info(step)
        time.sleep(20)
        status = self.primary_sh.get_db_cluster_status('status')
        self.assertTrue("Normal" in status, "执行失败" + step)

        step = '--step5:查看日志中的刷盘动作 expect:出现finish flush buffer--'
        self.log.info(step)
        new_flush_num = int(self.pri_user_node.sh(
            f'source {macro.DB_ENV_PATH};grep "finish flush buffer" '
            f'{macro.PG_LOG}/dn_6001/*.log|wc -l').result())
        self.assertTrue(new_flush_num > self.flush_num, "执行失败" + step)

    def tearDown(self):
        self.log.info('--还原环境--')
        self.conf_file = os.path.join(
            macro.DB_INSTANCE_PATH, macro.DB_PG_CONFIG_NAME)
        pri_result = self.com.get_sh_result(
            self.pri_user_node, f"mv {self.conf_file}_bak {self.conf_file}")
        st1_result = self.com.get_sh_result(
            self.st1_user_node, f"mv {self.conf_file}_bak {self.conf_file}")
        st2_result = self.com.get_sh_result(
            self.st2_user_node, f"mv {self.conf_file}_bak {self.conf_file}")
        stop_res = self.primary_sh.exec_cm_ctl("stop")
        start_res = self.primary_sh.exec_cm_ctl("start")
        self.log.info(pri_result)
        self.log.info(st1_result)
        self.log.info(st2_result)
        self.log.info(stop_res)
        self.log.info(start_res)
        self.assertIn(
            self.constant.cm_stop_success_msg, stop_res, "停止集群失败")
        self.assertIn(
            self.constant.cm_start_success_msg, start_res, "启动集群失败")
        self.log.info(f'----{os.path.dirname(__file__)} end----')
